﻿using System;
using System.Collections.Generic;

namespace TrinityEngine.SceneManagement
{
    public class Scene
    {
        private List<GameObject> _goList;

        public string name;

        public Camera Camera;

        private bool _isUnload;

        public Scene(string name = "")
        {
            _goList = new List<GameObject>();
            this.name = string.IsNullOrEmpty(name) ? GetType().Name : name;
            Camera = new Camera();
            _isUnload = false;
        }

        public void AddGameObject(GameObject go)
        {
            go.SetScene(this);
            _goList.Add(go);
        }

        public void RemoveGameObject(GameObject go)
        {
            _goList.Remove(go);
        }

        public void UnLoad()
        {
            _isUnload = true;

            for (int i = 0; i < _goList.Count; i++)
            {
                _goList[i].DestroyImmediate();
                _goList.RemoveAt(i--);
            }
        }

        public void FixedUpdate()
        {
            if (_isUnload)
            {
                return;
            }

            for (int i = 0; i < _goList.Count; i++)
            {
                if (!_goList[i].activeSelf)
                {
                    continue;
                }

                _goList[i].CallFixedUpdate();
            }
        }

        public void Update()
        {
            if (_isUnload)
            {
                return;
            }

            for (int i = 0; i < _goList.Count; i++)
            {
                if (!_goList[i].activeSelf)
                {
                    continue;
                }

                _goList[i].CallUpdate();

                if (_goList[i].isDestroyed)
                {
                    _goList[i].DestroyImmediate();
                    _goList.RemoveAt(i--);
                }
            }
        }

        public void Render()
        {
            if (_isUnload)
            {
                return;
            }

            foreach (GameObject go in _goList)
            {
                if (go.isUI)
                {
                    continue;
                }

                go.CallRender();
            }
        }

        public void RenderUI()
        {
            if (_isUnload)
            {
                return;
            }

            foreach (GameObject go in _goList)
            {
                if (!go.isUI)
                {
                    continue;
                }

                go.CallRender();
            }
        }
    }
}
